<?php
namespace app\index\controller;

use app\BaseController;
use think\facade\Db;

class Car extends BaseController
{
  public function list () 
  {
    $user = json_decode(session('user'), true);
    if (!$user) {
      returnJson(-2, '请先登录！');
    }
    $list = Db::table('shop_car')
    ->alias('c')
    ->join('shop_goods g','c.goods_id = g.id')
    ->field('c.id,c.num,g.id as goods_id,g.name,g.act_price,g.img')
    ->where('c.uid', $user['id'])
    ->select();
    if (!$list) {
      returnJson(-2, '查询失败！');
    }
    returnJson(0, '成功！', $list);
  }

  public function add_car () 
  {
    $user = json_decode(session('user'), true);
    if (!$user) {
      returnJson(-2, '请先登录！');
    }
    $goods_id = request()->param('goods_id');

    // 追加
    $car = Db::table('shop_car')->where('goods_id', $goods_id)->where('uid', $user['id'])->find();
    if ($car) {
      $update = Db::table('shop_car')->where('id', $car['id'])->inc('num')->update();
      if ($update >= 0) {
        returnJson(0, '添加成功！');
      }
    }

    // 添加
    $data = [
      'goods_id' => $goods_id,
      'num' => 1,
      'uid' => $user['id'],
    ];
    $update = Db::table('shop_car')->save($data);
    if ($update >= 0) {
      returnJson(0, '添加成功！');
    }
    returnJson(-2, '添加失败！');

  }

  public function update_num () 
  {
    $user = json_decode(session('user'), true);
    if (!$user) {
      returnJson(-2, '请先登录！');
    }
    $num = request()->param('num');
    $id = request()->param('id');
    if (!$id || !$num ) {
      returnJson(-2, '参数错误！');
    }
    $list = Db::table('shop_car')->where('id', $id)->update(['num'=>$num]);
    if (!$list) {
      returnJson(-2, '查询失败！');
    }
    returnJson(0, '成功！', $list);
  }


  public function delete ()
  {
    $ids = request()->param('ids');
    $idsArr = explode(',', $ids);
    if (is_array($idsArr)){
      $del = Db::table('shop_car')->delete($idsArr);
      returnJson(0, '删除成功！');
    }
    returnJson(-2, '删除失败！');
  }



}